package com.aat.func.pross;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.StringTokenizer;

public class TestGetSystemInfo {
	

	public static void main(String[] args) {
		System.out.println(isWindowsOrLinux());
	}

	/**
	 * 判断是服务器的系统类型是Windows 还是 Linux
	 * 
	 * @return
	 */
	public static String isWindowsOrLinux() {
		String osName = System.getProperty("os.name");
		String sysName = "";
		if (osName.toLowerCase().startsWith("windows")) {
			sysName = "windows";
		} else if (osName.toLowerCase().startsWith("linux")) {
			sysName = "linux";
		} else if (osName.toLowerCase().startsWith("mac")) {
			sysName = "macos";
		}
		return sysName;
	}

	/**
	 * windows环境下获取JVM的PID
	 */
	public String getJvmPIDOnWindows() {
		RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
		String pid = runtime.getName().split("@")[0];
		return pid;
	}

	/**
	 * linux环境下获取JVM的PID
	 */
	public String getJvmPIDOnLinux() {
		String command = "pidof java";
		BufferedReader in = null;
		Process pro = null;
		try {
			pro = Runtime.getRuntime().exec(new String[] { "sh", "-c", command });
			in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			StringTokenizer ts = new StringTokenizer(in.readLine());
			String pid = ts.nextToken();
			return pid;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getMemoryRateForLinux() {
		Process pro = null;
		Runtime r = Runtime.getRuntime();
		String remCount = "";
		try {
			String command = "top -b -n 1 -H -p " + getJvmPIDOnLinux();
			pro = r.exec(command);
			BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			in.readLine();
			in.readLine();
			in.readLine();
			in.readLine();
			in.readLine();
			in.readLine();
			in.readLine();
			StringTokenizer ts = new StringTokenizer(in.readLine());
			int i = 1;
			while (ts.hasMoreTokens()) {
				i++;
				ts.nextToken();
				if (i == 10) {
					remCount = ts.nextToken();
				}
			}
			in.close();
			pro.destroy();
		} catch (Exception e) {
		}
		return remCount;
	}

}
